package com.renrenyou.duanshipin.util;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @Description: 获取文件夹，文件大小
 * @Author: Created by qixu.
 * @CreatDate: 2022/3/24 14:51
 */
public class FileSizeUtil {
    private static final String TAG = FileSizeUtil.class.getSimpleName();
    public static final int SIZETYPE_B = 1;//获取文件大小单位为B的double值
    public static final int SIZETYPE_KB = 2;//获取文件大小单位为KB的double值
    public static final int SIZETYPE_MB = 3;//获取文件大小单位为MB的double值
    public static final int SIZETYPE_GB = 4;//获取文件大小单位为GB的double值

    /**
     * 获取文件指定文件的指定单位的大小
     *
     * @param file     文件
     * @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB
     * @return double值的大小
     */
    public static double getFileOrFilesSize(File file, int sizeType) {
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FormatFileSize(blockSize, sizeType);
    }

    /**
     * 调用此方法自动计算指定文件或指定文件夹的大小
     *
     * @param filePath 文件路径
     * @return 计算好的带B、KB、MB、GB的字符串
     */
    public static long getAutoFileOrFilesSize(String filePath) {
        if (filePath == null) {
            return 0;
        }
        File file = new File(filePath);
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return blockSize;
    }

    /**
     * 获取指定文件大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    private static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis;
            fis = new FileInputStream(file);
            size = fis.available();
        }
        return size;
    }

    /**
     * 获取指定文件夹
     *
     * @param f
     * @return
     * @throws Exception
     */
    private static long getFileSizes(File f) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSizes(flist[i]);
            } else {
                size = size + getFileSize(flist[i]);
            }
        }
        return size;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    public static String FormatFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1000) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1000000) {
            fileSizeString = df.format((double) fileS / 1000) + "KB";
        } else if (fileS < 1000000000) {
            fileSizeString = df.format((double) fileS / 1000000) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1000000000) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 转换文件大小,指定转换的类型
     *
     * @param fileS
     * @param sizeType
     * @return
     */
    public static double FormatFileSize(long fileS, int sizeType) {
        DecimalFormat df = new DecimalFormat("#.00");
        double fileSizeLong = 0;
        switch (sizeType) {
            case SIZETYPE_B:
                fileSizeLong = Double.parseDouble(df.format((double) fileS));
                break;
            case SIZETYPE_KB:
                fileSizeLong = Double.parseDouble(df.format((double) fileS / 1024));
                break;
            case SIZETYPE_MB:
                fileSizeLong = Double.parseDouble(df.format((double) fileS / (1024 * 1024)));
                break;
            case SIZETYPE_GB:
                fileSizeLong = Double.parseDouble(df.format((double) fileS / (1024 * 1024 * 1024)));
                break;
            default:
                break;
        }
        return fileSizeLong;
    }


    /**
     * 删除最早的视频文件
     */
    public static boolean deleteEarlyVideoFile(File file) {
        List<File> list = listFileSortByModifyTime(file);
        if (list.size() > 0) {
            return list.get(0).delete();
        }
        return false;
    }

    /**
     * 获取目录下所有文件(按时间排序)
     *
     * @param file
     * @return
     */
    public static List<File> listFileSortByModifyTime(File file) {
        List<File> list = getFiles(file);
        if (list.size() > 0) {
            list.sort(Comparator.comparingLong(File::lastModified));
        }
        return list;
    }

    /**
     * 获取目录下所有文件
     */
    public static List<File> getFiles(File realFile) {
        List<File> files = new ArrayList<>();
        if (realFile.isDirectory()) {
            File[] subFiles = realFile.listFiles();
//            for (File file : subFiles) {
//                if (file.isDirectory()) {
//                    getFiles(file);
//                } else {
//                    files.add(file);
//                }
//            }
            if (subFiles != null) {
                files.addAll(Arrays.asList(subFiles));
            }
        }
        return files;
    }

    /**
     * 获取URI对应的真实文件路径
     */
    public static String getRealPathFromUri(Context context, Uri contentUri) {
        if (contentUri == null) {
            return null;
        }
        String result = null;

        // 检查是否是文档类型的URI
        if (DocumentsContract.isDocumentUri(context, contentUri)) {
            // 外部存储文档
            if (isExternalStorageDocument(contentUri)) {
                final String docId = DocumentsContract.getDocumentId(contentUri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // 下载文档
            else if (isDownloadsDocument(contentUri)) {
                final String id = DocumentsContract.getDocumentId(contentUri);
                if (id.startsWith("raw:")) {
                    return id.substring(4);
                }

                final Uri contentUriDownloads = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.parseLong(id));

                return getDataColumn(context, contentUriDownloads, null, null);
            }
            // 媒体文档
            else if (isMediaDocument(contentUri)) {
                final String docId = DocumentsContract.getDocumentId(contentUri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUriMedia = null;
                if ("image".equals(type)) {
                    contentUriMedia = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUriMedia = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUriMedia = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUriMedia, selection, selectionArgs);
            }
        }
        // MediaStore (和其他基于内容的提供者)
        else if ("content".equalsIgnoreCase(contentUri.getScheme())) {
            if (isGooglePhotosUri(contentUri)) {
                return contentUri.getLastPathSegment();
            }
            return getDataColumn(context, contentUri, null, null);
        }
        // 文件
        else if ("file".equalsIgnoreCase(contentUri.getScheme())) {
            return contentUri.getPath();
        }

        return result;
    }

    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = MediaStore.Images.Media.DATA;
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}
